package com.zhuchaooasystem.ui.home.fragment.oa.record;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.adapter.holder.RecordDetailHolder;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.entity.RecordDetailEntity;
import com.zhuchaooasystem.entity.RecordEntity;
import com.zhuchaooasystem.entity.UserInfo;
import com.zhuchaooasystem.presenter.home.fragment.oa.record.RecordDetailContract;
import com.zhuchaooasystem.presenter.home.fragment.oa.record.RecordDetailPresenter;
import com.zhuchaooasystem.utils.ToastUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RecordDetailActivity extends BaseActivity<RecordDetailPresenter> implements RecordDetailContract.View {

    @BindView(R.id.actionbar_iv_back)
    ImageView iv_back;
    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    @BindView(R.id.act_record_detail_txt_name)
    TextView txt_name;
    @BindView(R.id.act_record_detail_txt_date)
    TextView txt_date;
    @BindView(R.id.act_record_detail_txt_topic)
    TextView txt_topic;
    @BindView(R.id.act_record_detail_txt_remark)
    TextView txt_remark;
    @BindView(R.id.act_record_detail_recycle)
    EasyRecyclerView recycle;

    //----
    private UserInfo user;
    private RecordEntity.ResultBean.SuccessfulBean record;
    //----
    private int cur_position; //当前播放录音文件的index,值为0表示没有播放
    private MediaPlayer mediaPlayer;
    //----
    private List<RecordDetailEntity.ResultBean.SuccessfulBean> recordDetailList;
    private RecyclerArrayAdapter recordDetailAdapter;
    //----
    private Handler handler = new Handler();

    @Override
    protected int getLayout() {
        return R.layout.activity_record_detail;
    }

    @Override
    protected RecordDetailPresenter getPresenter() {
        return new RecordDetailPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        if (null != getIntent() && null != getIntent().getExtras()) {
            record = getIntent().getExtras().getParcelable("record");
        } else {
            ToastUtil.showShort(mContext, "出错了，请重试~");
            finish();
        }
        cur_position = -1;
        //----
        user = UserInfo.getInstance();
        //----
        initMediaPlayer();
    }

    @Override
    protected void initView() {
        txt_title.setText(getString(R.string.actionbar_title_record_detail));
        iv_back.setVisibility(View.VISIBLE);
        //----
        initTopView();
        //----
        recycle.setLayoutManager(new LinearLayoutManager(mContext));
        recycle.setAdapterWithProgress(recordDetailAdapter = new RecyclerArrayAdapter(mContext) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new RecordDetailHolder(parent, RecordDetailActivity.this);
            }
        });

    }

    private void initTopView() {
        //----
        txt_name.setText(user.getUserName());
        txt_date.setText("创建时间：" + record.getServiceTime());
        txt_topic.setText("录音主题：" + record.getTheme());
        txt_remark.setText("录音备注：" + record.getRemark());
    }

    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();
            }
        });
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                ToastUtil.showShort(mContext, "该文件无法播放");
                cur_position = -1;
                recordDetailAdapter.notifyDataSetChanged();
                return false;
            }
        });
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                cur_position = -1;
                recordDetailAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initDataAndLoadData() {
        //----
        mPresenter.getRecordDetail(record.getItemId());
    }


    @OnClick({R.id.actionbar_iv_back})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                finish();
                break;
        }
    }


    @Override
    public void refreshData(List<RecordDetailEntity.ResultBean.SuccessfulBean> data) {
        this.recordDetailList = data;
        recordDetailAdapter.clear();
        recordDetailAdapter.addAll(data);
    }

    @Override
    public void onClickPlay(final int position) {
        if (cur_position == position) {
            if (mediaPlayer.isPlaying()) {
                cur_position = -1;
                recordDetailAdapter.notifyDataSetChanged();
                mediaPlayer.stop();
            } else {
                cur_position = position;
                recordDetailAdapter.notifyDataSetChanged();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mediaPlayer.reset();
                            mediaPlayer.setDataSource(recordDetailList.get(position).getFilePath());
                            mediaPlayer.prepareAsync();
                        } catch (Exception e) {
                        }
                    }
                }, 1000);

            }
        } else {
            cur_position = position;
            recordDetailAdapter.notifyDataSetChanged();
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(recordDetailList.get(position).getFilePath());
                        mediaPlayer.prepareAsync();
                    } catch (Exception e) {
                    }
                }
            }, 1000);
        }
    }

    public int getCur_position() {
        return cur_position;
    }

    public void setCur_position(int cur_position) {
        this.cur_position = cur_position;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mediaPlayer) {
            mediaPlayer.stop();
            //释放资源
            mediaPlayer.release();
        }
    }
}
